﻿using System;
using System.IO;
using System.Windows;
using System.Linq;
using System.Windows.Media;
using System.Xml;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.AvalonEdit.Highlighting.Xshd;

namespace EffectEd
{
    /// <summary>
    /// Interaction logic for ChooseTemplateWindow.xaml
    /// </summary>
    public partial class ChooseTemplateWindow : Window
    {
        public ChooseTemplateWindow()
        {
            InitializeComponent();
            LoadTemplates();
            using (var reader = new XmlTextReader(DataFiles.GetAbsolutePath("hlsl10.xshd")))
            {
                editPreview.SyntaxHighlighting = HighlightingLoader.Load(reader, HighlightingManager.Instance);
            }
            editPreview.TextEditor.IsReadOnly = true;
            editPreview.TextEditor.FontSize = 10;
            editPreview.TextEditor.BorderThickness = new Thickness(1);
            editPreview.TextEditor.BorderBrush = new SolidColorBrush(Colors.Gray);
            editPreview.LineNumberMargin.Visibility = Visibility.Collapsed;
            if (listBoxTemplates.Items.Count > 0) listBoxTemplates.SelectedIndex = 0;
        }

        public string SelectedFilename
        {
            get { return (string)listBoxTemplates.SelectedValue; }
        }

        private void LoadTemplates()
        {
            DataFiles.GetAbsolutePath("templates");
            listBoxTemplates.ItemsSource =
                Directory.GetFiles(DataFiles.GetAbsolutePath("templates"), "*.fx").OrderBy(f => f).Select(
                    f => new Tuple<string, string>(GetDisplayName(f), f));
        }

        private string GetDisplayName(string filename)
        {
            var displayName = Path.GetFileNameWithoutExtension(filename);
            if (displayName.Contains("$")) displayName = displayName.Substring(displayName.IndexOf('$') + 1);
            return displayName;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = true;
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
        }

        private void listBoxTemplates_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (listBoxTemplates.SelectedItems.Count > 0)
            {
                buttonOk.IsEnabled = true;
                editPreview.Text = File.ReadAllText((string)listBoxTemplates.SelectedValue);
            }
        }

        private void listBoxTemplates_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (listBoxTemplates.SelectedItems.Count > 0)
            {
                DialogResult = true;
            }
        }
    }
}
